<template>
    <!-- use the modal component, pass in the prop -->
    <modal v-if="stateManager.editDialogVisible"
           @cancel="closeDialog"
           @ok="saveModel"
           :modal-title="modalTitle"
           elId="box"
           model-size="large">
        <!--
          you can use custom content here to overwrite
          default content
        -->
        <div class="row" v-if="!loading">
            <div class="row">
                <div class="col-xs-12">
                    <div class="tabs-container" id="myTab">
                        <ul class="nav nav-tabs">
                            <li v-bind:class="{ active: nowIndex ==0 }"><a v-on:click="toggleTabs(0)" data-toggle="tab"
                                                                           href="#tab-1"> 人员</a></li>
                            <li v-bind:class="{ active: nowIndex ==1 }"><a v-on:click="toggleTabs(1)" data-toggle="tab"
                                                                           href="#tab-2">组织</a></li>
                            <li v-bind:class="{ active: nowIndex ==2 }"><a v-on:click="toggleTabs(2)" data-toggle="tab"
                                                                           href="#tab-2">内容</a></li>
                        </ul>
                        <div class="tab-content">
                            <div id="tab-1" class="tab-pane" v-bind:class="{ active: nowIndex ==0 }">
                                <div class="panel-body">
                                    <div class="col-lg-12">
                                        <div class="row">
                                            <div class="col-lg-4">
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <div class="ibox-tools">
                                                            <h5>组织</h5>
                                                        </div>
                                                    </div>
                                                    <div class="ibox-content">
                                                        <div style="width:300px; margin:10px;">
                                                            <ZTree
                                                                    ref='tree'
                                                                    :treeData="treeData"
                                                                    :options="options"
                                                                    @node-click="itemChange"
                                                            />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-lg-8">
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <div class="ibox-tools">
                                                            <h5>接收人员</h5>
                                                            <button class="btn btn-primary btn-xs" :disbaled="onOrg"
                                                                    v-on:click="allOrgToSelect()">
                                                                全选<i class="fa fa-caret-square-o-right"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="ibox-content">
                                                        <vue-table :data-source="tableList"
                                                                   :queryString="model.selectOrgId">
                                                            <template slot="search">

                                                            </template>
                                                            <template slot="header">
                                                                <tr>
                                                                    <th>姓名</th>
                                                                    <th>学号</th>
                                                                    <th>操作</th>
                                                                </tr>
                                                            </template>
                                                            <template slot="tbody" slot-scope="props">

                                                                <tr>
                                                                    <td>{{props.item.u_name}}</td>
                                                                    <td>{{props.item.u_code}}</td>
                                                                    <td>
                                                                        <button title="选定"
                                                                                class="btn btn-white btn-xs m-b-none"
                                                                                v-on:click="addStudentToSelect(props.item)">
                                                                            <i class="fa fa-pencil list-btn-i"></i> 选定
                                                                        </button>
                                                                    </td>

                                                                </tr>

                                                            </template>
                                                        </vue-table>
                                                    </div>
                                                </div>

                                            </div>
                                            <div class="col-lg-12">
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <h5>已选人员</h5>
                                                    </div>
                                                    <div class="ibox-content">
                                                        <ul class="row">
                                                            <div class="student-item list-group-item"
                                                                 v-for=" (item,key) in model.selectStudent">
                                                                <button type="button"
                                                                        class="btn btn-xs btn-outline btn-primary pull-right"
                                                                        v-on:click="removeStudent(key)">取消
                                                                </button>
                                                                {{item.u_name}}
                                                            </div>
                                                        </ul>
                                                    </div>
                                                </div>

                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div id="tab-2" class="tab-pane" v-bind:class="{ active: nowIndex ==1 }">
                                <div class="panel-body">
                                    <div class="col-lg-12">
                                        <div class="row">
                                            <div class="col-lg-8">
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <h5>接收组织</h5>
                                                        <div class="ibox-tools">
                                                            <button class="btn btn-primary btn-xs" :disbaled="onOrg"
                                                                    v-on:click="addOrgToSelect()">
                                                                添加 <i class="fa fa-caret-square-o-right"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="ibox-content">
                                                        <div id="app" style="width:300px; margin:10px;">
                                                            <ZTree
                                                                    ref='tree'
                                                                    :treeData="treeData"
                                                                    :options="options"
                                                                    @node-click="itemClick"
                                                            />
                                                        </div>
                                                    </div>
                                                </div>

                                            </div>
                                            <div class="col-lg-4">
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <h5>已选组织</h5>
                                                    </div>
                                                    <div class="ibox-content org-list-group">
                                                        <ul class="list-group">
                                                            <li class="list-group-item"
                                                                v-for=" (item,key) in model.selectOrg">
                                                                <button type="button"
                                                                        class="btn btn-xs btn-outline btn-primary pull-right"
                                                                        v-on:click="removeOrg(key)">取消
                                                                </button>
                                                                {{item.label}}
                                                            </li>
                                                        </ul>
                                                    </div>
                                                </div>

                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="tab-3" class="tab-pane" v-bind:class="{ active: nowIndex ==2}">
                                <div class="panel-body">
                                    <div class="col-lg-12">
                                        <div class="row">
                                            <div class="col-lg-6">
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <h5>消息编辑</h5>
                                                    </div>
                                                    <div class="ibox-content">
                                                        <vue-form-item label="公众号选择">
                                                            <div class="i-checks"
                                                                 style="display: inline-block;margin-right: 20px"
                                                                 v-for="(item ,key) in $store.state.weChat_name">
                                                                <checkbox style="font-size: 1rem;"
                                                                          :value="key"
                                                                          v-model="model.WeChat"
                                                                >{{item}}
                                                                </checkbox>
                                                            </div>
                                                        </vue-form-item>
                                                        <div class="hr-line-dashed"></div>
                                                        <vue-form-item label="链接地址"
                                                                       :error-message="errors.first('url')">
                                                            <input-text v-model:value="model.url"
                                                                        v-validate="'required|href'"
                                                                        label="链接地址"
                                                                        el-name="url"></input-text>
                                                        </vue-form-item>
                                                        <div v-for="(item,key) in changeItem">
                                                            <vue-form-item :label="item.desc"
                                                                           :error-message="errors.first('item'+key)">
                                                                <input-text v-model:value="item.value"
                                                                            v-validate="'required'"
                                                                            :label="item.desc"
                                                                            :el-name="'item'+key"></input-text>
                                                            </vue-form-item>
                                                        </div>
                                                        <!--<div class="text-center">-->
                                                        <!--<button class="btn btn-primary" v-on:click="saveModel()" style="width: 300px">发送</button>-->
                                                        <!--</div>-->
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-lg-6">
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <h5>标准范例</h5>
                                                    </div>
                                                    <div class="ibox-content" v-html="model.desc">
                                                        {{model.desc}}
                                                    </div>
                                                </div>
                                                <div class="hr-line-dashed"></div>
                                                <div class="ibox float-e-margins">
                                                    <div class="ibox-title">
                                                        <h5>预览</h5>
                                                    </div>
                                                    <div class="ibox-content">
                                                        <p v-for="item in changeItem">
                                                            {{item.desc}}{{item.value}}
                                                        </p><br>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12" v-if="loading">
            <div class="spiner-example">
                <div class="sk-spinner sk-spinner-cube-grid">
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                    <div class="sk-cube"></div>
                </div>
            </div>
        </div>

    </modal>
</template>
<style>
    .student-item {
        display: inline-block;
        margin: 2px;
        width: 24%;
    }

    .item-handle-area .label {
        opacity: 0.6;
        background-color: transparent;
    }

    .select-from {
        font-size: 10px;
    }

    .total {
        width: 100px;
    }

    .org-list-group {
        height: 750px;
        overflow-y: auto
    }
</style>
<script>
    export default {
        props: {
            stateManager: {
                type: Object
            }
        },
        data: function () {
            return {
                loading: false,
                list: this.$listDataSource({
                    url: 'api/student-search'
                }),
                model: this.$modelDataSource({
                    url: '/api/WeChat/WeChatTemplate',
                    dataKey: 'model',
                    attributes: {
                        id: 0,
                        desc: '',
                        items: [],
                        itemlist: [],
                        WeChat: [],
                        url: '',
                        user: [],
                        selectStudent: [],
                        selectOrg: [],
                        org: [],
                        selectOrgId: '0'
                    }
                }),
                onOrg: {},
                options: {
                    rootName: '软件学院',
                    showCheckbox: false,
                    halfCheck: false,//控制父框是否需要半钩状态
                    iconStyle: {                        // custom icon style, sometimes u just need to set color
                        color: '#18a689'                // default #000
                    }
                },
                refreshList: false,
                treeData: [],
                nowIndex: 0
            }
        },
        methods: {
            changeUserList: function () {
                this.refreshList = true;
            },
            allOrgToSelect: function () {
                for (let i = 0; i < this.list.items.length; i++) {
                    this.model.selectStudent.push(this.list.items[i]);
                }
                this.model.selectStudent = this.arrUnique(this.model.selectStudent);
                this.model.user = this.refureStudentArray(this.model.selectStudent);
            },
            toggleTabs: function (index) {
                this.nowIndex = index;
            },
            closeDialog: function () {
                this.model.reset();
                this.stateManager.editModelId = 0;
                this.stateManager.editDialogVisible = false;
                this.model.selectOrg.length = 0;
                this.model.user.length = 0;
                this.model.org.length = 0;
                this.model.selectStudent.length =0;
                this.treeData = [];
                this.onOrg = '';
                this.nowIndex = 0;
                this.refreshList = true;
            },
            mounted: function () {
                this.loadTreeData();
            },
            saveModel: function () {
                let self = this;
                self.validate(function () {
                    if (self.checkItem()) {
                        self.loading = true;
                        self.model.save(function () {
                            self.loading = false;
                            self.closeDialog();
                            toastr.success(self.model.name + '发送成功！');
                        }, function () {
                            self.loading = false;
                            if (self.model.errors.permissions_errors) {
                                toastr.error(self.model.errors.permissions_errors);
                            } else {
                                toastr.error('缺少关键数据');
                            }
                        });
                    }
                });
            },
            feachArray: function (treeData = []) {
                let str = [];
                for (let i = 0; i < treeData.length; i++) {
                    str[i] = treeData[i].id
                }
                return str;
            },
            validate: function (successCallback, failedCallback) {
                let _this = this;
                this.$validator.validateAll().then(() => {
                    // eslint-disable-next-line
                    console.log('验证通过');
                    typeof successCallback === 'function' && successCallback();
                }).catch(() => {
                    // eslint-disable-next-line
                    console.log('验证未通过');
                    typeof failedCallback === 'function' && failedCallback();
                });

            },
            checkItem() {
                let str = '';
                if (this.model.WeChat.length == 0) {
                    str += '请选择公众账号';
                    toastr.error(str);
                    return false;
                } else {
                    return true;
                }
            },
            generateKey(treeData = [], parentKey) {
                treeData = treeData.map((item, i) => {
                    item.key = item.id;
                    return item;
                })
                return treeData;
            },
            loadTreeData: function () {
                this.treeData = this.$store.state.organizational;
                this.treeData = this.generateKey(this.treeData, 0);
            },
            itemClick: function (node) {
                this.onOrg = node;
            },
            itemChange: function (node) {
                // console.log(node)
                this.model.selectOrgId = node.id;
                this.changeUserList()
            },
            addOrgToSelect() {
                if(this.onOrg.id>0){
                    this.model.selectOrg.push(this.onOrg);
                    this.model.selectOrg = this.arrUnique(this.model.selectOrg);
                    this.model.org = this.refureArry(this.model.selectOrg);
                    this.onOrg = ''
                }
            },
            removeOrg(key) {
                this.model.selectOrg.splice(key, 1)
            },
            removeStudent(key) {
                this.model.selectStudent.splice(key, 1)
            },
            addStudentToSelect(obj) {
                this.model.selectStudent.push(obj);
                this.model.selectStudent = this.arrUnique(this.model.selectStudent);
                this.model.user = this.refureStudentArray(this.model.selectStudent);
            },
            refureStudentArray(arr) {
                let result = [];
                for (let i = 0; i < arr.length; i++) {
                    result.push(arr[i].u_code);
                }
                return result;
            },
            refureArry(arr) {
                let result = [];
                for (let i = 0; i < arr.length; i++) {
                    result.push(arr[i].id);
                }
                return result;
            },
            arrUnique(arr) {
                let result = [], hash = {};
                for (let i = 0, elem; (elem = arr[i]) != null; i++) {
                    if (!hash[elem.id]) {
                        result.push(elem);
                        hash[elem.id] = true;
                    }
                }
                return result;
            }

        },
        computed: {
            modalTitle: function () {
                return '发送模板消息';
            },
            changeItem: function () {
                if (this.model.id != 0) {
                    let items = [];
                    for (let j = 0; j < this.model.items.length; j++) {
                        let item = {name: '', value: null, desc: ''};
                        item.name = this.model.items[j].name;
                        item.desc = this.model.items[j].desc;
                        items.push(item);
                    }
                    this.model.itemlist = items;
                    return this.model.itemlist
                }
            },
            tableList() {
                //let self = this;
                if (this.refreshList) {
                    console.log(this.model.selectOrgId);
                    this.list.fetch({query: this.model.selectOrgId});
                    this.refreshList = false;
                }
                return this.list;
            }
        },
        watch: {
            'stateManager.editModelId': function (newValue) {
                this.model.fetch(newValue);
                this.loadTreeData();
            }
        }
    }
</script>